<template>
  <view class="product-create-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="title">新增采购商品</text>
    </view>

    <!-- 主表单 -->
    <view class="form-container">
      <!-- 基础信息 -->
      <view class="form-section">
        <view class="section-title">基础信息</view>
        <view class="form-item">
          <view class="form-label">商品名称</view>
          <input
              v-model="form.productName"
              placeholder="请输入商品名称"
              class="form-input"
          />
        </view>
        <view class="form-item">
          <view class="form-label">商品条码</view>
          <input
              v-model="form.barcode"
              placeholder="自动生成请留空"
              class="form-input"
          />
        </view>
      </view>

      <!-- 分类与供应商 -->
      <view class="form-section">
        <view class="section-title">分类与供应商</view>
        <view class="form-item" @click="openCategoryModal">
          <view class="form-label">商品分类</view>
          <view class="form-value">
            <text>{{ selectedCategoryPath || '请选择分类' }}</text>
            <uni-icons type="arrowright" size="24"></uni-icons>
          </view>
        </view>
        <view class="form-item" @click="openSupplierModal">
          <view class="form-label">供应商</view>
          <view class="form-value">
            <text>{{ selectedSupplierName || '请选择供应商' }}</text>
            <uni-icons type="arrowright" size="24"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 价格信息 -->
      <view class="form-section">
        <view class="section-title">价格信息</view>
        <view class="form-item">
          <view class="form-label">销售类型</view>
          <picker mode="selector" :range="priceTypes" :range-key="'label'" @change="onPriceTypeChange">
            <view class="form-value">
              <text>{{ getPriceTypeLabel(form.priceType) || '请选择销售类型' }}</text>
              <uni-icons type="arrowright" size="24"></uni-icons>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <view class="form-label">默认采购价</view>
          <view class="price-input">
            <text class="currency-prefix">¥</text>
            <input
                type="digit"
                v-model="form.defaultPurchasePrice"
                placeholder="请输入价格"
                class="price-value"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="form-label">默认销售价</view>
          <view class="price-input">
            <text class="currency-prefix">¥</text>
            <input
                type="digit"
                v-model="form.defaultSellingPrice"
                placeholder="请输入价格"
                class="price-value"
            />
          </view>
        </view>
      </view>

      <!-- 图片信息 -->
      <view class="form-section">
        <view class="section-title">商品图片</view>
        <view class="form-item">
          <view class="form-label">主图</view>
          <view class="image-container">
            <view
                class="upload-area"
                @click="chooseImage"
            >
              <uni-icons type="plusempty" size="60"></uni-icons>
              <text class="upload-text">上传图片</text>
            </view>
            <view
                class="preview-image"
                v-if="form.defaultImageUrl"
            >
              <image :src="form.defaultImageUrl" mode="aspectFill"></image>
              <view class="delete-overlay" @click="removeImage">
                <uni-icons type="closeempty" size="36"></uni-icons>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-button" @click="submitForm">
      保存商品
    </view>

    <!-- 分类选择模态框 -->
    <view class="modal-mask" v-if="showCategoryModal">
      <view class="modal-container">
        <view class="modal-header">
          <view class="header-title">
            <text class="modal-title">选择分类</text>
            <view class="breadcrumb" v-if="categoryPath.length > 0">
              <text
                  v-for="(item, index) in categoryPath"
                  :key="index"
                  @click="goToLevel(index)"
              >
                {{ item.name }}
                <text v-if="index !== categoryPath.length - 1"> /</text>
              </text>
            </view>
          </view>
          <uni-icons
              type="closeempty"
              size="36"
              class="close-btn"
              @click="closeCategoryModal"
          ></uni-icons>
        </view>
        <view class="category-list">
          <view
              class="category-item"
              v-for="category in currentCategoryList"
              :key="category.id"
              @click="handleCategoryClick(category)"
          >
            <view class="category-content">
              <text :style="{ paddingLeft: category.level * 24 + 'rpx' }">{{ category.name }}</text>
            </view>
            <uni-icons
                v-if="category.children && category.children.length > 0"
                type="arrowright"
                size="24"
            ></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 供应商选择模态框 -->
    <view class="modal-mask" v-if="showSupplierModal">
      <view class="modal-container">
        <view class="modal-header">
          <view class="header-title">
            <text class="modal-title">选择供应商</text>
          </view>
          <uni-icons
              type="closeempty"
              size="36"
              class="close-btn"
              @click="closeSupplierModal"
          ></uni-icons>
        </view>
        <view class="supplier-list">
          <view
              class="supplier-item"
              v-for="supplier in suppliers"
              :key="supplier.id"
              @click="selectSupplier(supplier)"
          >
            <view class="supplier-content">
              <text class="supplier-name">{{ supplier.name }}</text>
              <text class="supplier-desc">{{ supplier.desc }}</text>
            </view>
            <!--            <uni-icons type="checkmarkempty" size="24"></uni-icons>-->
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        operatorId:this.$store.state.user.id,
        productName: '',
        barcode: '',
        categoryId: null,
        supplierId: 1,
        defaultPurchasePrice: '',
        defaultSellingPrice: '',
        defaultImageUrl: '',
        priceType: 'WEIGHT' // 新增售价类型字段
      },
      categories: [
        {
          id: 1,
          name: '食品饮料',
          level: 1,
          children: [
            {
              id: 11,
              name: '碳酸饮料',
              level: 2,
              children: [
                {id: 111, name: '可乐', level: 3},
                {id: 112, name: '雪碧', level: 3}
              ]
            },
            {id: 12, name: '乳制品', level: 2}
          ]
        },
        {
          id: 2,
          name: '生鲜果蔬',
          level: 1,
          children: [
            {id: 21, name: '水果', level: 2, children: [{id: 211, name: '苹果', level: 3}]}
          ]
        }
      ],
      suppliers: [
        {id: '1', name: '供应商A', desc: '主营食品饮料'},
        {id: '2', name: '供应商B', desc: '主营生鲜果蔬'},
        {id: '3', name: '供应商C', desc: '综合供应商'}
      ],
      showCategoryModal: false,
      showSupplierModal: false,
      currentCategoryList: [],
      categoryPath: [],
      selectedCategoryPath: '',
      selectedSupplierName: '',
      windowHeight: 0,
      contentHeight: 0,
      priceTypes: [
        { value: 'NORMAL', label: '按件' },
        { value: 'WEIGHT', label: '称重' },
        { value: 'BULK', label: '散装' },
        { value: 'COMBO', label: '组合套装' },
        { value: 'TIME', label: '计时' },
        { value: 'AREA', label: '按面积' },
        { value: 'LENGTH', label: '按长度' },
        { value: 'CUSTOM', label: '自定义' }
      ],
      // 默认配置
      defaultConfig: {
        categoryId: 2, // 默认分类ID：碳酸饮料
        supplierId: 'S002', // 默认供应商ID：供应商A
        priceType: 'WEIGHT' // 默认售价类型：按件
      }
    };
  },

  onLoad() {
    this.currentCategoryList = this.categories;
    this.getWindowInfo();
    this.initDefaultValues(); // 初始化默认值
  },

  onResize() {
    this.getWindowInfo();
  },

  computed: {
    // 计算是否需要滚动
    needScroll() {
      return this.contentHeight > this.windowHeight;
    }
  },

  methods: {
    // 初始化默认值
    initDefaultValues() {
      // 设置默认分类
      const defaultCategory = this.findCategoryById(this.defaultConfig.categoryId);
      if (defaultCategory) {
        this.form.categoryId = defaultCategory.id;
        this.selectedCategoryPath = this.generatePath(defaultCategory);
      }

      // 设置默认供应商
      const defaultSupplier = this.suppliers.find(s => s.id === this.defaultConfig.supplierId);
      if (defaultSupplier) {
        this.form.supplierId = defaultSupplier.id;
        this.selectedSupplierName = defaultSupplier.name;
      }

      // 设置默认售价类型
      this.form.priceType = this.defaultConfig.priceType;
    },

    // 查找分类
    findCategoryById(id) {
      const findInList = (list) => {
        for (const item of list) {
          if (item.id === id) return item;
          if (item.children) {
            const found = findInList(item.children);
            if (found) return found;
          }
        }
        return null;
      };

      return findInList(this.categories);
    },

    // 获取窗口信息
    getWindowInfo() {
      uni.getSystemInfo({
        success: (res) => {
          this.windowHeight = res.windowHeight;
        }
      });

      // 计算内容高度（简化版，实际项目中可能需要更精确的计算）
      setTimeout(() => {
        const query = uni.createSelectorQuery();
        query.select('.product-create-page').boundingClientRect((rect) => {
          if (rect) {
            this.contentHeight = rect.height;
          }
        }).exec();
      }, 300);
    },

    // 打开分类模态框
    openCategoryModal() {
      this.showCategoryModal = true;
    },

    // 关闭分类模态框
    closeCategoryModal() {
      this.showCategoryModal = false;
      this.currentCategoryList = this.categories;
      this.categoryPath = [];
    },

    // 分类点击处理
    handleCategoryClick(category) {
      if (category.children && category.children.length > 0) {
        this.categoryPath.push(category);
        this.currentCategoryList = category.children;
      } else {
        this.form.categoryId = category.id;
        this.selectedCategoryPath = this.generatePath(category);
        this.closeCategoryModal();
      }
    },

    // 生成分类路径
    generatePath(category) {
      return [...this.categoryPath.map(item => item.name), category.name].join(' / ');
    },

    // 返回指定层级
    goToLevel(level) {
      this.categoryPath = this.categoryPath.slice(0, level + 1);
      this.currentCategoryList = level === -1
          ? this.categories
          : this.categoryPath[level].children;
    },

    // 打开供应商模态框
    openSupplierModal() {
      this.showSupplierModal = true;
    },

    // 关闭供应商模态框
    closeSupplierModal() {
      this.showSupplierModal = false;
    },

    // 选择供应商
    selectSupplier(supplier) {
      this.form.supplierId = supplier.id;
      this.selectedSupplierName = supplier.name;
      this.closeSupplierModal();
    },

    // 图片选择
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.form.defaultImageUrl = res.tempFilePaths[0];
        }
      });
    },

    // 删除图片
    removeImage() {
      this.form.defaultImageUrl = '';
    },

    // 价格验证
    validatePrice() {
      const {defaultPurchasePrice, defaultSellingPrice} = this.form;
      if (defaultPurchasePrice && isNaN(parseFloat(defaultPurchasePrice))) {
        this.form.defaultPurchasePrice = '';
        uni.showToast({title: '采购价格式错误', icon: 'none'});
      }
      if (defaultSellingPrice && isNaN(parseFloat(defaultSellingPrice))) {
        this.form.defaultSellingPrice = '';
        uni.showToast({title: '销售价格式错误', icon: 'none'});
      }
    },

    // 售价类型选择处理
    onPriceTypeChange(e) {
      this.form.priceType = this.priceTypes[e.detail.value].value;
    },

    // 获取售价类型标签
    getPriceTypeLabel(value) {
      const item = this.priceTypes.find(item => item.value === value);
      return item ? item.label : '';
    },

    // 提交表单
    submitForm() {
      const {productName, categoryId, supplierId, defaultPurchasePrice, defaultSellingPrice, priceType} = this.form;
      console.log(this.form)
      if (!productName) return uni.showToast({title: '请输入商品名称', icon: 'none'});
      if (!categoryId) return uni.showToast({title: '请选择商品分类', icon: 'none'});
      if (!supplierId) return uni.showToast({title: '请选择供应商', icon: 'none'});
      if (!priceType) return uni.showToast({title: '请选择售价类型', icon: 'none'}); // 新增验证
      // if (!defaultPurchasePrice) return uni.showToast({title: '请输入采购价格', icon: 'none'});
      // if (!defaultSellingPrice) return uni.showToast({title: '请输入销售价格', icon: 'none'});

      uni.showLoading({title: '提交中...'});
      // 模拟API请求
      // 调用提交接口（示例）
      this.req({
        url: '/product/add',
        method: 'POST',
        data: this.form
      }).then(res => {
        uni.hideLoading();
        console.log(res)
        uni.showToast({title: '保存成功', icon: 'success'});
        // 重置表单（保留分类、供应商和售价类型）
        this.resetForm();
      })

    },

    // 重置表单（修改后：保留分类、供应商和售价类型）
    resetForm() {
      // 保存当前的分类、供应商和售价类型
      const savedCategoryId = this.form.categoryId;
      const savedSupplierId = this.form.supplierId;
      const savedPriceType = this.form.priceType;
      const savedCategoryPath = this.selectedCategoryPath;
      const savedSupplierName = this.selectedSupplierName;

      // 重置表单，保留需要的值
      this.form = {
        productName: '',
        barcode: '',
        categoryId: savedCategoryId,
        supplierId: savedSupplierId,
        defaultPurchasePrice: '',
        defaultSellingPrice: '',
        defaultImageUrl: '',
        priceType: savedPriceType
      };

      // 恢复保留的值
      this.selectedCategoryPath = savedCategoryPath;
      this.selectedSupplierName = savedSupplierName;
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.product-create-page {
  padding: 30rpx;
  background-color: #f7f7f7;
  box-sizing: border-box;
}

.page-header {
  padding: 30rpx 0;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #2c3e50;
}

/* 表单容器 */
.form-container {
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 120rpx; /* 为底部固定按钮留出空间 */
}

.form-section {
  padding: 20rpx 30rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #666;
  margin-bottom: 20rpx;
  padding-left: 15rpx;
  border-left: 4rpx solid #007aff;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 180rpx;
  font-size: 30rpx;
  color: #333;
}

.form-input {
  flex: 1;
  font-size: 30rpx;
  color: #666;
  padding-left: 20rpx;
}

.form-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 20rpx;
  font-size: 30rpx;
  color: #666;
}

.price-input {
  flex: 1;
  display: flex;
  align-items: center;
  padding-left: 20rpx;
}

.currency-prefix {
  font-size: 32rpx;
  color: #333;
  margin-right: 10rpx;
}

.price-value {
  flex: 1;
  font-size: 32rpx;
  color: #666;
  text-align: right;
}

.image-container {
  flex: 1;
  display: flex;
  padding-left: 20rpx;
}

.upload-area {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  margin-right: 30rpx;
}

.upload-text {
  font-size: 24rpx;
  margin-top: 10rpx;
}

.preview-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.preview-image image {
  width: 100%;
  height: 100%;
}

.delete-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s;
}

.preview-image:hover .delete-overlay {
  opacity: 1;
}

.submit-button {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  height: 90rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 34rpx;
  border-radius: 45rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 6rpx 20rpx rgba(0, 122, 255, 0.2);
  z-index: 999;
}

/* 模态框样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  width: 90%;
  max-height: 80%;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 25rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f8f8;
  border-bottom: 1rpx solid #eee;
}

.header-title {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.modal-title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
}

.breadcrumb {
  font-size: 24rpx;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.breadcrumb text {
  cursor: pointer;
  margin-right: 10rpx;
}

.breadcrumb text:hover {
  color: #007aff;
}

.close-btn {
  color: #999;
}

.category-list {
  flex: 1;
  overflow-y: auto;
}

.category-item {
  padding: 25rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.2s;
}

.category-item:hover {
  background-color: #f8f8f8;
}

.category-content {
  flex: 1;
  display: flex;
  align-items: center;
}

.supplier-list {
  flex: 1;
  overflow-y: auto;
}

.supplier-item {
  padding: 25rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #f5f5f5;
}

.supplier-content {
  flex: 1;
}

.supplier-name {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.supplier-desc {
  font-size: 26rpx;
  color: #999;
}
</style>